package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private ShoppingCartMapper shoppingCartMapper;
    @Resource
    private AddressBookMapper addressBookMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private WebSocketServer webSocketServer;

    /**
     * 提交订单
     * @param ordersDTO
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersDTO) {
        //前端会传递地址id 订单表中有收货人信息
        AddressBook addressBook = addressBookMapper.getById(ordersDTO.getAddressBookId());
        if(Objects.isNull(addressBook)){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //订单明细
        //查询购物车,为了订单明细
        //查询当前用户的购物车
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectShoppingCart(BaseContext.getCurrentId());
        if (CollectionUtils.isEmpty(shoppingCarts)){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //构建主表订单
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersDTO,orders);
        //手机号
        orders.setPhone(addressBook.getPhone());
        //详细地址
        orders.setAddress(addressBook.getDetail());
        //收获人
        orders.setConsignee(addressBook.getConsignee());
        //订单号
        String number = String.valueOf(System.currentTimeMillis());
        orders.setNumber(number);
        //订单状态
        //没完成微信付款流程,直接把状态改为待结单
        //待付款
        orders.setStatus(Orders.PENDING_PAYMENT);
        //用户ID
        orders.setUserId(BaseContext.getCurrentId());
        //订单时间
        LocalDateTime now = LocalDateTime.now();
        orders.setOrderTime(now);
        //支付状态
        //orders.setPayStatus(Orders.UN_PAID);
        //付款状态改为已支付
        orders.setPayStatus(Orders.PAID);
        //状态改为已支付
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        //新增订单到数据库
        orderMapper.insertOrder(orders);

        //构建订单明细
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            //赋值主表订单id
            orderDetail.setOrderId(orders.getId());
            //把对象添加到List集合中
            orderDetails.add(orderDetail);
        }
        //批量新增到数据库
        orderDetailMapper.insertList(orderDetails);

        //清空购物车
        shoppingCartMapper.emptyShoppingCart(BaseContext.getCurrentId());

        //构建结果
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderNumber(number);
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderTime(now);

        //来单提醒
        HashMap map = new HashMap<>();
        map.put("type",Orders.PENDING_PAYMENT);
        map.put("orderId",orders.getId());
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

        return orderSubmitVO;
    }

    /**
     * 查询历史订单(订单分页查询)
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult queryOrderFrom(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page =orderMapper.queryOrder(ordersPageQueryDTO);
        for (OrderVO ordersVO : page) {
            ordersVO.setOrderDetailList(orderDetailMapper.selectOrderDetailById(ordersVO.getId()));
        }
        return PageResult.builder().total(page.getTotal()).records(page.getResult()).build();
    }

    /**
     *订单id查订单
     * @param id
     * @return
     */
    @Override
    public OrderVO selectOrderById(Long id) {
        OrderVO orderVO = orderMapper.selectOrderById(id);
        orderVO.setOrderDetailList(orderDetailMapper.selectOrderDetailById(id));
        return orderVO;
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        if(orders.getUserId() != null && orderMapper.getStatusById(ordersCancelDTO.getId()).equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException("订单已在派送,如需取消请联系商家!");
        }
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        //如果订单是已支付状态,则给用户退款
        if(orders.getPayStatus().equals(Orders.PAID)){
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setStatus(Orders.CANCELLED);
        orderMapper.updateOrderStatus(orders);
    }

    /**
     * 再来一单
     * @param id 订单id
     */
    @Override
    public void repetition(Long id) {
        //到订单明细表查询该id对应的菜品
        List<ShoppingCart> list = orderDetailMapper.selectByOrderId(id);

        for (ShoppingCart shoppingCart : list) {
            //添加时间
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartMapper.add(shoppingCart);
        }
    }

    /**
     * 各个订单状态数量
     * @return
     */
    @Override
    public OrderStatisticsVO selectStatistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(orderMapper.statusCount(Orders.CONFIRMED));           //待派送
        orderStatisticsVO.setDeliveryInProgress(orderMapper.statusCount(Orders.DELIVERY_IN_PROGRESS));  //派送中
        orderStatisticsVO.setToBeConfirmed(orderMapper.statusCount(Orders.TO_BE_CONFIRMED));       //待接单
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        if (orderMapper.getStatusById(ordersConfirmDTO.getId()).equals(Orders.TO_BE_CONFIRMED)){
            orders.setId(ordersConfirmDTO.getId());
            orders.setStatus(Orders.CONFIRMED);
            orderMapper.updateOrderStatus(orders);
        }

    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejectionOrder(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders();
        orders.setId(ordersRejectionDTO.getId());   //订单id
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason()); //拒单理由
        orders.setPayStatus(Orders.REFUND);
        orders.setStatus(Orders.CANCELLED); //状态 : 已取消
        orderMapper.updateOrderStatus(orders);
    }

    /**
     * 派送
     * @param id
     */
    @Override
    public void deliveryOrder(Long id) {
        Orders orders = new Orders();
        if(orderMapper.getStatusById(id).equals(Orders.CONFIRMED)){
            orders.setId(id);
            orders.setStatus(Orders.DELIVERY_IN_PROGRESS);  //状态改为派送中
            orderMapper.updateOrderStatus(orders);
        }
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void compleOrder(Long id) {
        Orders orders = new Orders();
        if(orderMapper.getStatusById(id).equals(Orders.DELIVERY_IN_PROGRESS)){
            orders.setId(id);
            orders.setStatus(Orders.COMPLETED);  //状态改为派送中
            orderMapper.updateOrderStatus(orders);
        }
    }

    /**
     * 催单
     */
    @Override
    public void reminder(Long id) {
        OrderVO orderVO = orderMapper.selectOrderById(id);
        if(orderVO == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        HashMap map = new HashMap();
        map.put("type",Orders.TO_BE_CONFIRMED);
        map.put("orderId",id);
        map.put("content", "订单号：" + orderVO.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
